﻿using DevelopAssistant.Service;
using ICSharpCode.WinFormsUI.Docking;
using NORM.Common;
using NORM.DataBase;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace DevelopAssistant.Core.DBMS
{
    public partial class TableDesignnerDocument : DockContent
    {
        int max_rowIndex = 0;
        string table = string.Empty;
        DataBaseServer server = null;

        private ComboBox DropDownDataTypes = new ComboBox();

        protected MainForm OwnerForm { get; set; }

        public TableDesignnerDocument()
        {
            InitializeComponent();
            InitializeControls();
            this.dgv_design.CellClick += new DataGridViewCellEventHandler(this.dataGridView1_CellClick);
            this.dgv_design.RowPostPaint += new DataGridViewRowPostPaintEventHandler(dataGridView1_RowPostPaint);            
        }

        public TableDesignnerDocument(MainForm mainForm,string tableName, DataBaseServer dataBaseServer)
            : this()
        {
            table = tableName;
            server = dataBaseServer;
            OwnerForm = (MainForm)mainForm;
            this.textBox1.Text = table;
            BindDataTypes(server.ProviderName);
        }

        public void InitializeControls()
        {
            this.dgv_design.Controls.Add(DropDownDataTypes);          
            this.DropDownDataTypes.Visible = false;
            this.DropDownDataTypes.BackColor = Color.White;
            this.DropDownDataTypes.DropDownStyle = ComboBoxStyle.DropDownList;
            this.panel1.TopBlackColor = Color.WhiteSmoke;
            this.panel1.BottomBlackColor = SystemColors.Control;
            this.DropDownDataTypes.SelectedValueChanged += DropDownDataTypes_SelectedValueChanged;
        }

        private void LoadXTheme()
        {           
            this.panel1.BorderColor = OwnerForm.XTheme.FormBorderOutterColor;
        }

        private void TableDesignnerDocument_Load(object sender, EventArgs e)
        {
            LoadXTheme();
            GetTableColumns();
        }

        private void GetTableColumns()
        {
            max_rowIndex = 0; 
            using (var db = Utility.GetAdohelper(server))
            {
                DataTable dt = db.GetTableObject(table);
                DataTable dv = new DataTable();
                dv.Columns.Add(new DataColumn("序号", typeof(Int32)));
                dv.Columns.Add(new DataColumn("名称", typeof(String)));
                dv.Columns.Add(new DataColumn("数据类型", typeof(String)));
                dv.Columns.Add(new DataColumn("长度", typeof(String)));
                dv.Columns.Add(new DataColumn("主键标识", typeof(String)));
                dv.Columns.Add(new DataColumn("允许为空", typeof(String)));
                dv.Columns.Add(new DataColumn("自增标识", typeof(String)));
                dv.Columns.Add(new DataColumn("描述", typeof(String)));
                dv.Columns.Add(new DataColumn("全标识", typeof(String)));

                int index = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow row = dv.NewRow();
                    string ColumnOrder = dr["colorder"] + "";
                    string ColumnName = dr["ColumnName"] + "";
                    string ColumnTypeName = dr["TypeName"] + "";
                    string ColumnLength = dr["Length"] + "";
                    string ColumnIsNull = dr["CisNull"] + "";
                    string ColumnIdentity = dr["CisNull"] + "";
                    string ColumnPrimaryKey = dr["CisNull"] + "";

                    row["序号"] = index;
                    if (!string.IsNullOrEmpty(ColumnOrder))
                    {
                        row["序号"] = Int32.Parse(ColumnOrder);
                    }
                    row["名称"] = ColumnName;

                    switch (ColumnTypeName.ToLower())
                    {
                        case "int":
                        case "int32":
                        case "int64":
                        case "number":
                        case "image":
                        case "bit":
                        case "integer":
                            ColumnLength = "";
                            break;
                    }

                    row["数据类型"] = ColumnTypeName.ToLower();
                    row["长度"] = ColumnLength;

                    //if (ColumnIsNull.Contains("not null"))
                    //{
                    //    ColumnIdentity = "×";//Identity
                    //}
                    //else
                    //{
                    //    ColumnIdentity = "√";
                    //}

                    //if (ColumnIsNull.Contains("pk"))
                    //{
                    //    ColumnIdentity += " P";
                    //}

                    //if (ColumnIsNull.Contains("identity"))
                    //{
                    //    ColumnIdentity += " ↑";
                    //}

                    if (ColumnIsNull.Contains("pk"))
                    {
                        ColumnPrimaryKey = "Pk";
                    }
                    else
                    {
                        ColumnPrimaryKey = "";
                    }

                    row["主键标识"] = ColumnPrimaryKey;

                    if (ColumnIsNull.Contains("identity"))
                    {
                        ColumnIdentity = "自增";
                    }
                    else
                    {
                        ColumnIdentity = "";
                    }

                    row["自增标识"] = ColumnIdentity;

                    if (ColumnIsNull.Contains("not null"))
                    {
                        ColumnIsNull = "False";
                    }
                    else
                    {
                        ColumnIsNull = "True";
                    }

                    row["允许为空"] = Boolean.Parse(ColumnIsNull);
                    row["全标识"] = dr["CisNull"] + "";


                    dv.Rows.Add(row);
                    index++;
                    max_rowIndex++;
                }

                dgv_design.DataSource = dv.DefaultView;
            }
        }

        private void toolStripButtonReturn_Click(object sender, EventArgs e)
        {
            GetTableColumns();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                if (e.ColumnIndex == 2)
                {
                    DataGridViewCell cell = dgv_design.Rows[e.RowIndex].Cells[e.ColumnIndex];//dataGridView1.CurrentCell; //
                    Rectangle rect = dgv_design.GetCellDisplayRectangle(cell.ColumnIndex, cell.RowIndex, false);
                    DropDownDataTypes.Left = rect.X;
                    DropDownDataTypes.Top = rect.Y;
                    DropDownDataTypes.Width = rect.Width;
                    DropDownDataTypes.Height = rect.Height;
                    DropDownDataTypes.Visible = true;

                    DropDownDataTypes.SelectedItem = cell.Value;

                    if (cell.RowIndex == max_rowIndex && (cell.Value + "") == "")
                    {
                        cell.Value = (string)DropDownDataTypes.SelectedItem;
                    }

                }
                else if (e.ColumnIndex == 4)
                {
                    DropDownDataTypes.Visible = false;                    
                }
                else
                {
                    DropDownDataTypes.Visible = false;
                }
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                var value = dgv_design.Rows[e.RowIndex].Cells[4].Value;
                if (value != null && value != DBNull.Value)
                {
                    if (value.ToString().Contains("Pk"))
                    {
                        Graphics g = e.Graphics;
                        e.Graphics.DrawImage(this.imageList1.Images[0], e.RowBounds.Left + 18, e.RowBounds.Top + (e.RowBounds.Height - 16) / 2, 16f, 16f);//绘制图标
                    }
                }
            }
        }

        private void btnApplyOk_Click(object sender, EventArgs e)
        {
            SaveChange();
            //this.DialogResult = DialogResult.OK;
            //this.Close();
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BindDataTypes(string ProviderName)
        {
            string DataBaseTypes = "Sql";
            switch (ProviderName)
            {
                case "System.Data.SQL":
                case "System.Data.Sql":
                    DataBaseTypes = "Sql";
                    break;
                case "System.Data.Sqlite":
                    DataBaseTypes = "Sqlite";
                    break;
                case "System.Data.PostgreSql":
                    DataBaseTypes = "PostgreSql";
                    break;
            }

            string path = Application.StartupPath + "\\" + "DataBaseDataTypes.xml";
            if (System.IO.File.Exists(path))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(path);
                XmlNodeList list = xmldoc.SelectSingleNode(string.Format("{0}{1}{2}", 
                    "//", DataBaseTypes, "DataBase")).ChildNodes;

                foreach (XmlNode li in list)
                {
                    ToolStripMenuItem item = new ToolStripMenuItem();
                    item.Text = li.Attributes["DataType"].Value + "";
                    this.DropDownDataTypes.Items.Add(item.Text);
                }

            }
            else
            {
                MessageBox.Show("DataBaseDataTypes.xml文件不存在");
            }

          
        }

        private void DropDownDataTypes_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                ComboBox cbox = (ComboBox)sender;
                DataGridViewCell DCell = dgv_design.CurrentCell;
                if (DCell != null)
                {
                    dgv_design.CurrentCell.Value = cbox.Text;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            SaveChange();
        }

        private void SaveChange()
        {
            StringPlus sp = new StringPlus();
            sp.Append("SET ANSI_NULLS ON");
            sp.Append(Environment.NewLine);
            sp.Append("GO");
            sp.Append(Environment.NewLine);
            sp.Append("SET QUOTED_IDENTIFIER ON");
            sp.Append(Environment.NewLine);
            sp.Append("GO");
            sp.Append(Environment.NewLine);
            sp.Append(Environment.NewLine);
            sp.Append("SET ANSI_PADDING ON");
            sp.Append(Environment.NewLine);
            sp.Append("GO");            
            sp.Append(Environment.NewLine);
            sp.Append(Environment.NewLine);
            
            switch (server.ProviderName)
            {
                case "System.Data.Sql":
                case "System.Data.SQL":
                    sp.Append("CREATE TABLE [dbo].[" + this.textBox1.Text + "](");
                    break;
                case "System.Data.Sqlite":
                    sp.Append("CREATE TABLE [" + this.textBox1.Text + "](");
                    break;
                case "System.Data.PostgreSql":
                    sp.Append("CREATE TABLE \"" + this.textBox1.Text + "\"(");
                    break;
            }

            sp.Append(Environment.NewLine);

            int index = 0;
            var dt = (this.dgv_design.DataSource as DataView).Table;

            List<Column> PrimaryKeyList = new List<Column>();
            List<Column> IdentityList = new List<Column>();

            foreach (DataRow row in dt.Rows)
            {
                string identity = row["自增标识"] + "";
                string isnull = row["允许为空"] + "";
                string parmaryKey = row["主键标识"] + "";                
                string sqldataType= SnippetBase.getDataBaseDataType(row["数据类型"] + "", row["长度"] + "", server.ProviderName);

                Column col = new Column();
                col.Name = row["名称"] + "";

                if (!string.IsNullOrEmpty(isnull) && Boolean.Parse(isnull))
                {
                    isnull = "NULL";
                    col.IsNull = "NULL";
                }
                else
                {
                    isnull = "NOT NULL";
                    col.IsNull = "NOT NULL";
                }

                if (identity == "自增")
                {
                    identity = "IDENTITY(1,1)";
                    col.Auto_Identify = true;
                    IdentityList.Add(col);
                }              
                           
                col.Len = row["长度"] + "";
                col.DataType = row["数据类型"] + "";               

                if(index>0)
                {
                    sp.Append("  ," + SnippetBase.GetColumnName(row["名称"] + "", server.ProviderName) + " " + sqldataType + " " + identity + " " + isnull + "");
                }
                else
                {
                    sp.Append("   " + SnippetBase.GetColumnName(row["名称"] + "", server.ProviderName) + " " + sqldataType + " " + identity + " " + isnull + "");
                }

                if (parmaryKey == "Pk")
                {
                    col.Pk_Identify = true;  
                    PrimaryKeyList.Add(col);
                }

                sp.Append(Environment.NewLine);
                index++;
            }

            sp.Append(")");           
            sp.Append(Environment.NewLine);
            sp.Append("GO");
            sp.Append(Environment.NewLine);
            sp.Append(Environment.NewLine);
            sp.Append("SET ANSI_PADDING OFF");
            sp.Append(Environment.NewLine);
            sp.Append("GO");

            using (var db = DevelopAssistant.Service.Utility.GetAdohelper(server))
            {
                string createTable = sp.Value;

                db.BeginTransaction();

                try
                {
                    bool havethistable = false;                     
                    var result = db.GetDataBaseObject().Select("table_name='" + this.textBox1.Text + "' and table_type='table' ");
                    if (result != null && result.Count() > 0)
                        havethistable = true;

                    DataTable column_dt = db.GetTableObject(this.textBox1.Text, DataBaseSchema.Table);

                    if (havethistable)
                    {
                        string renameTable = string.Empty;
                        switch (server.ProviderName)
                        {
                            case "System.Data.Sql":
                            case "System.Data.SQL":
                                renameTable = "EXEC sp_rename '" + this.textBox1.Text + "','" + "_tem_" + this.textBox1.Text + "'";
                                break;
                            case "System.Data.Sqlite":
                                renameTable = "ALTER TABLE " + server.DataBaseName + "." + this.textBox1.Text + " RENAME TO " + "_tem_" + this.textBox1.Text + ";";
                                break;
                            case "System.Data.PostgreSql":
                                renameTable = "ALTER TABLE " + this.textBox1.Text + " RENAME TO " + "_tem_" + this.textBox1.Text + ";";
                                break;
                        }

                        db.Execute(CommandType.Text, renameTable, null);
                    }

                    createTable = createTable.Replace("GO", " ");
                    db.Execute(CommandType.Text, createTable, null);

                    if (havethistable)
                    {
                        int rowscount = 0;
                        string copyDataTable = "select count(*) from " + SnippetBase.GetTableName("_tem_" + this.textBox1.Text, server.ProviderName) + "";
                                               
                        DataTable rowcount_dt = db.GetDataSet(CommandType.Text, copyDataTable, null).Tables[0];
                        if (rowcount_dt != null && rowcount_dt.Rows.Count > 0)
                        {
                            Int32.TryParse(rowcount_dt.Rows[0][0] + "", out rowscount);
                        }

                        copyDataTable = string.Empty;
                        if (rowscount > 1000000) //1000000 百万
                        {
                            if (MessageBox.Show(this,
                                "郑重提示,数据超过100万,将只保留前100万条数据,是否要继续操作?","郑重提示",
                                MessageBoxButtons.OKCancel).Equals(DialogResult.OK))
                            {
                                int colIndex = 0;
                                string _columns = string.Empty;

                                foreach (DataRow dr in dt.Rows)
                                {
                                    if (this.RowsContains(dr["名称"] + "", "ColumnName", column_dt))
                                    {
                                        if (colIndex > 0)
                                            _columns += "," + SnippetBase.GetColumnName(dr["名称"] + "", server.ProviderName);
                                        else
                                            _columns += " " + SnippetBase.GetColumnName(dr["名称"] + "", server.ProviderName);
                                        colIndex++;
                                    }
                                }

                                if (IdentityList.Count > 0)
                                    copyDataTable += "SET IDENTITY_INSERT " + SnippetBase.GetTableName(this.textBox1.Text, server.ProviderName) + " ON ";

                                copyDataTable += Environment.NewLine;
                                copyDataTable += "INSERT INTO " + SnippetBase.GetTableName(this.textBox1.Text, server.ProviderName) + " (" + _columns + ") ";
                                copyDataTable += Environment.NewLine;

                                switch (server.ProviderName)
                                {
                                    case "System.Data.SQL":
                                    case "System.Data.Sql":
                                        copyDataTable += "SELECT TOP 1000000 " + _columns + "";
                                        copyDataTable += " FROM " + SnippetBase.GetTableName("_tem_" + this.textBox1.Text + "", server.ProviderName) + " ";
                                        break;
                                    case "System.Data.Sqlite":
                                        copyDataTable += "SELECT " + _columns + "";
                                        copyDataTable += " FROM " + SnippetBase.GetTableName("_tem_" + this.textBox1.Text + "", server.ProviderName) + " LIMIT 1000000; ";
                                        break;
                                    case "System.Data.PostgreSql":
                                        copyDataTable += "SELECT " + _columns + "";
                                        copyDataTable += " FROM " + SnippetBase.GetTableName("_tem_" + this.textBox1.Text + "", server.ProviderName) + " LIMIT 1000000; ";
                                        break;
                                }

                                copyDataTable += Environment.NewLine;

                                if (IdentityList.Count > 0)
                                    copyDataTable += "SET IDENTITY_INSERT " + SnippetBase.GetTableName(this.textBox1.Text, server.ProviderName) + " OFF";

                                db.Execute(CommandType.Text, copyDataTable, null);
                            }
                        }
                        else
                        {                         
                            int colIndex = 0;
                            string _columns = string.Empty;
                           
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (this.RowsContains(dr["名称"] + "","ColumnName",column_dt))
                                {
                                    if (colIndex > 0)
                                        _columns += "," + SnippetBase.GetColumnName(dr["名称"] + "", server.ProviderName);
                                    else
                                        _columns += " " + SnippetBase.GetColumnName(dr["名称"] + "", server.ProviderName);
                                    colIndex++;
                                }
                            }

                            if (IdentityList.Count > 0)
                                copyDataTable += "SET IDENTITY_INSERT " + SnippetBase.GetTableName(this.textBox1.Text, server.ProviderName) + " ON ";

                            copyDataTable += Environment.NewLine;
                            copyDataTable += "INSERT INTO " + SnippetBase.GetTableName(this.textBox1.Text,server.ProviderName) + " (" + _columns + ") ";
                            copyDataTable += Environment.NewLine;
                            copyDataTable += "SELECT " + _columns + "";
                            copyDataTable += " FROM " + SnippetBase.GetTableName("_tem_" + this.textBox1.Text + "", server.ProviderName)+" ";
                            copyDataTable += Environment.NewLine;

                            if (IdentityList.Count > 0)
                                copyDataTable += "SET IDENTITY_INSERT " + SnippetBase.GetTableName(this.textBox1.Text, server.ProviderName) + " OFF";

                            db.Execute(CommandType.Text, copyDataTable, null);

                        }

                        string dropTable = "Drop Table " + SnippetBase.GetTableName("_tem_" + this.textBox1.Text, server.ProviderName) + "";
                        db.Execute(CommandType.Text, dropTable, null);

                    }

                    //最后处理主键 
                    string PrimaryKeyTable = string.Empty;
                    foreach (var col in PrimaryKeyList)
                        PrimaryKeyTable += addPrimaryKeySql(server.ProviderName, this.textBox1.Text, col.Name);

                    if (!string.IsNullOrEmpty(PrimaryKeyTable))
                        db.Execute(CommandType.Text, PrimaryKeyTable, null);

                    db.Commit();

                    MessageBox.Show("保存成功");
                }
                catch (Exception ex)
                {
                    db.RollBack();
                    MessageBox.Show(ex.Message);
                }                

            }
            
        }

        private bool RowsContains(string value, string column,DataTable table)
        {
            foreach (DataRow row in table.Rows)
            {
                if ((row[column] + "").Equals(value))
                    return true;
            }
            return false;
        }

        private string addPrimaryKeySql(string ProviderName, string tableName, string columnName)
        {
            string val = string.Empty;
            switch (ProviderName)
            {
                case "System.Data.Sql":
                case "System.Data.SQL":
                    val = "alter table [" + tableName + "] add constraint PK_" + tableName + " primary key([" + columnName + "])";
                    break;
                case "System.Data.Sqlite":
                    val = "alter table [" + tableName + "] add constraint PK_" + tableName + " primary key([" + columnName + "])";
                    break;
                case "System.Data.PostgreSql":
                    val = "alter table \"" + tableName + "\" add constraint \"PK_" + tableName + "\" primary key(\"" + columnName + "\")";
                    break;

            }
            return val;
        }

        private void dgv_design_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex > -1 && e.ColumnIndex == -1) 
                {                    
                    Rectangle rect= dgv_design.GetCellDisplayRectangle(1, e.RowIndex, true);
                    Point MousePt = new Point(e.X, e.Y);
                    MousePt.Offset(rect.X - dgv_design.RowHeadersWidth, rect.Y);
                    dgv_design.ClearSelection();                  
                    dgv_design.Rows[e.RowIndex].Selected = true;
                    contextMenuStrip1.Show(dgv_design, MousePt);                   
                }
            }
        }

        private void dgv_design_MouseClick(object sender, MouseEventArgs e)
        {
                     
        }

        private void 添加列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int selectedRowIndex = 0;
            if (dgv_design.SelectedRows.Count > 0)
                selectedRowIndex = dgv_design.SelectedRows[0].Index;
            else
                selectedRowIndex = dgv_design.Rows.Count;
          
            DataTable dt = (dgv_design.DataSource as DataView).Table;
            DataRow row = dt.NewRow();            
            row[5] = true;
            dt.Rows.InsertAt(row, selectedRowIndex);
        }

        private void 删除列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgv_design.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow row in dgv_design.SelectedRows)
                {
                    dgv_design.Rows.Remove(row);
                }                
            }
        }

        private void 上移ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgv_design.SelectedRows.Count > 0)
            {
                DataTable dt = ((DataView)dgv_design.DataSource).Table;
                int index = dgv_design.SelectedRows[0].Index;

                if (index > -1)
                {
                    int preIndex = index - 1;
                    int nextIndex = index + 1;

                    if (preIndex < 0)
                        preIndex = 0;

                    if (nextIndex > dt.Rows.Count - 1)
                        nextIndex = dt.Rows.Count - 1;

                    if (index != preIndex)
                    {
                        DataTable newdt = dt.Clone();
                        newdt.Rows.Clear();

                        DataRow dr1 = dt.Rows[index];
                        DataRow dr2 = dt.Rows[preIndex];

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (i == index)
                            {
                                newdt.ImportRow(dr2);
                            }
                            else if (i == preIndex)
                            {
                                newdt.ImportRow(dr1);
                            }
                            else
                            {
                                newdt.ImportRow(dt.Rows[i]);
                            }
                        }

                        dgv_design.DataSource = newdt.DefaultView;

                        SetDataGridViewSeletedRow(preIndex);

                        dgv_design.Invalidate();

                    }
                }
            }

        }

        private void 下移ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (dgv_design.SelectedRows.Count > 0)
            {
                DataTable dt = ((DataView)dgv_design.DataSource).Table;
                int index = dgv_design.SelectedRows[0].Index;

                if (index > -1)
                {
                    int preIndex = index - 1;
                    int nextIndex = index + 1;

                    if (preIndex < 0)
                        preIndex = 0;

                    if (nextIndex > dt.Rows.Count - 1)
                        nextIndex = dt.Rows.Count - 1;

                    if (index != nextIndex)
                    {
                        DataTable newdt = dt.Clone();
                        newdt.Rows.Clear();

                        DataRow dr1 = dt.Rows[index];
                        DataRow dr2 = dt.Rows[nextIndex];

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (i == index)
                            {
                                newdt.ImportRow(dr2);
                            }
                            else if (i == nextIndex)
                            {
                                newdt.ImportRow(dr1);
                            }
                            else
                            {
                                newdt.ImportRow(dt.Rows[i]);
                            }
                        }

                        dgv_design.DataSource = newdt.DefaultView;

                        SetDataGridViewSeletedRow(nextIndex);

                        dgv_design.Invalidate();

                    }
                }
            }
        }

        private void 设为主键ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgv_design.SelectedRows.Count > 0)
            {
                dgv_design.EndEdit();

                var cisnull = dgv_design.SelectedRows[0].Cells[5].Value;
                if (cisnull != null && cisnull != DBNull.Value && Boolean.Parse(cisnull + ""))
                {
                    MessageBox.Show("设为主键的列不能允许为空");
                    return;
                }                    

                foreach (DataGridViewRow row in dgv_design.Rows)
                {
                    var value = row.Cells[4].Value;
                    if (value != null && value != DBNull.Value)
                    {
                        if (value.ToString().Contains("Pk") && row.Index == dgv_design.SelectedRows[0].Index)
                            return;

                        if (value.ToString().Contains("Pk"))
                        {
                            row.Cells[4].Value = value.ToString().Replace("Pk", "");
                        }
                        else if (row.Index == dgv_design.SelectedRows[0].Index)
                        {
                            row.Cells[4].Value += "Pk" + value;
                        }
                        
                    }
                }

                ((dgv_design.DataSource) as DataView).Table.AcceptChanges();

                dgv_design.Invalidate();
            }            
        }

        private void SetDataGridViewSeletedRow(int index)
        {
            dgv_design.ClearSelection();
            dgv_design.Rows[index].Selected = true;
        }

    }
}
